package com.pos.toolbox.file;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;

import com.pos.set.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description:客户端安装相关方法
 * @author:Cai
 * @time:2014-6-30 下午1:15:28
 */
public class InstallUtils {

	/**
	 * 检测SD卡上最新APK是否已存在
	 * 
	 * @return 返回APK是否存在
	 */
	public static boolean isApkExist(Context context) {
		File file = new File(getApkFilePath(context));
		if (file.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * 检测SD卡上最新APK是否已存在
	 * 
	 * @return 返回APK是否存在
	 */
	public static boolean isUpdateApkExist(Context context, int code) {
		File file = new File(getUpdateApkFilePath(context, code));
		if (file.exists()) {
			return true;
		}
		return false;
	}

	/**
	 * 删除更新文件
	 */
	public static void deleteUpdateFile(Context context) {
		File file = new File(InstallUtils.getApkFilePath(context));
		if (file.exists()) {
			file.delete();
		}

	}

	/**
	 * 获取当前版本的app安装文件完整路径
	 */
	public static String getApkFilePath(Context context) {
		return context.getFilesDir().getAbsolutePath() + "/smartpos" + ".apk";
	}

	/**
	 * 获取升级版本的app安装文件完整路径
	 */
	public static String getUpdateApkFilePath(Context context, int code) {
		return context.getFilesDir().getAbsolutePath() + "/smartpos" + ".apk";
	}

	/**
	 * 通过url获取下载的文件名称（截取最后的/）
	 * 
	 * @param url
	 *            图片url
	 */
	public static String getFileNameFromUrl(String url) {
		int index = url.lastIndexOf("/");
		return url.substring(index + 1, url.length());
	}

	/**
	 * 获取文件（图片和视频）根路径
	 * 
	 */
	public static String getImageAndVideoHomePath() {
		String DIR_PATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "imageAndVideo";
		File destDir = new File(DIR_PATH);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		return DIR_PATH;
	}

	/**
	 * 通过url获取下载的文件（图片和视频）存放路径
	 * 
	 * @param url
	 *            图片url
	 */
	public static String getImageAndVideoPath(String url) {
		Log.out("getImageAndVideoPath", getImageAndVideoHomePath() + File.separator + getFileNameFromUrl(url));

		return getImageAndVideoHomePath() + File.separator + getFileNameFromUrl(url);
	}

	/**
	 * 检测SDCARD是否存在
	 * 
	 * @return
	 */
	public static boolean isSdcardMounted() {
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	/** 执行Linux命令，并返回执行结果。 */
	public static String exec(String[] args) {
		String result = "";
		ProcessBuilder processBuilder = new ProcessBuilder(args);
		Process process = null;
		InputStream errIs = null;
		InputStream inIs = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int read = -1;
			process = processBuilder.start();
			errIs = process.getErrorStream();
			while ((read = errIs.read()) != -1) {
				baos.write(read);
			}
			baos.write("/n".getBytes());
			inIs = process.getInputStream();
			while ((read = inIs.read()) != -1) {
				baos.write(read);
			}
			byte[] data = baos.toByteArray();
			result = new String(data);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (errIs != null) {
					errIs.close();
				}
				if (inIs != null) {
					inIs.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (process != null) {
				process.destroy();
			}
		}
		return result;
	}

	/**
	 * 检测APK是否已安装
	 * 
	 * @param pkgName
	 *            包名
	 * @return boolean
	 */
	public static boolean isApkInstalled(Context context, String pkgName) {
		try {
			context.getPackageManager().getPackageInfo(pkgName, 0);
			return true;
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
		}
		return false;
	}

	public static boolean copyApkFromAssets(Context context, String fileName, String path) {
		boolean copyIsFinish = false;
		try {
			InputStream is = context.getAssets().open("apk/" + fileName);
			File file = new File(path);
			file.createNewFile();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] temp = new byte[1024];
			int i = 0;
			while ((i = is.read(temp)) > 0) {
				fos.write(temp, 0, i);
			}
			fos.close();
			is.close();
			copyIsFinish = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return copyIsFinish;
	}

}
